﻿using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace NoSqlTest
{
    public class CalculateExecutionTime
    {
        private readonly RequestDelegate _next;//下一个中间件
        private readonly ILogger _logger;
        Stopwatch stopwatch;
        public CalculateExecutionTime(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }
            this._next = next ?? throw new ArgumentNullException(nameof(next));
            _logger = loggerFactory.CreateLogger<CalculateExecutionTime>();
        }

        public async Task Invoke(HttpContext context)
        {
            stopwatch = new Stopwatch();
            _logger.LogInformation($@"====接口{context.Request.Path}开始计时====");
            stopwatch.Start();//启动计时器
            await _next.Invoke(context);
            stopwatch.Stop();//停止秒表。
            _logger.LogInformation($@"====接口{context.Request.Path}耗时:{stopwatch.ElapsedMilliseconds}ms====");
        }
    }
}
